/*
 * Copyright 2008-2009 ArtisanLogic.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.artisanlogic.jingo.assembler;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

// =====================================================================================================================
// DefaultUrlMappingStrategy.java                                                                Created on Jan 27, 2009
// ---------------------------------------------------------------------------------------------------------------------
/**
 * This class is the default UrlMappingStrategy implementation.
 * 
 * @author john@artisanlogic.com
 * @author sean@artisanlogic.com
 * @since 0.9-Beta
 */
// =====================================================================================================================
public class DefaultUrlMappingStrategy implements UrlMappingStrategy {

  // -------------------------------------------------------------------------------------------------------------------
  // private instance fields
  // -------------------------------------------------------------------------------------------------------------------
  
	private final Map<String, URL> repositories = new HashMap<String, URL>();
  
  // -------------------------------------------------------------------------------------------------------------------
  // public instance methods
  // -------------------------------------------------------------------------------------------------------------------
	
	/**
	 * This method registers a repository identifier to URL binding to be used for Dependency to URL mapping.
	 * 
	 * @param id This parameter holds the repository identifier to be bound to the specified URL.
	 * @param url This parameter holds the URL to be bound to the specified identifier.
	 */
	public void addRepository(final String id, final URL url) {
		repositories.put(id, url);
	}

	/* (non-Javadoc)
	 * @see com.artisanlogic.jingo.assembler.UrlMappingStrategy#map(com.artisanlogic.jingo.assembler.Dependency)
	 */
	public URL map(final Dependency dependency) {
		URL repoUrl = repositories.get(dependency.getRepository());
		if(repoUrl != null) {
			try {
				return new URL(repoUrl, dependency.getModuleName().replace('.', '/') + ".js");
			} catch(Exception e) {
				throw new RuntimeException(e);
			}
		}
		return null;
	}
}
